<?php

namespace App\Http\Controllers;

use App\Exceptions\PasswordErrorException;
use App\Exceptions\UserNotFoundException;
use App\Models\LoginRecord;
use App\Models\User;
use App\Services\KongOauthService;
use App\Services\PasswordService;

class LoginController extends Controller
{
    /*
     * @api post /admin-api/a/login 登录
     * @version 0.0.1
     * @group admin
     *
     * @param body string mobile 手机号
     * @param body string password 密码
     * @param body string nonce 验证码
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function login()
    {
        $this->validate($this->request, [
            'mobile' => 'required|regex:/^1[345789]\d{9}$/',
            'password' => 'required|alpha_dash|between:6,32',
        ]);
        $mobile = $this->request->input('mobile');
        $password = $this->request->input('password');
        /** @var User $userObj */
        $userObj = User::where('mobile', $mobile)->first();
        if (empty($userObj)) {
            throw new UserNotFoundException();
        }
        if (!PasswordService::verify($password, $userObj->getPassword())) {
            throw new PasswordErrorException();
        }
        $scope = User::getUserAllScopes($userObj->getId());
        // 记录登录信息
        $loginRecordObj = new LoginRecord();
        $loginRecordObj->setUserId($userObj->getId());
        $loginRecordObj->setName($userObj->getName());
        $loginRecordObj->setMobile($userObj->getMobile());
        $loginRecordObj->setScope(implode(',', $scope));
        $loginRecordObj->setIp($this->request->getClientIp());
        $loginRecordObj->setUserAgent($this->request->header('user_agent', ''));
        $loginRecordObj->save();
        $result = KongOauthService::getToken($userObj->getId(), $scope);
        return $this->sendSuccessJson($result);
    }

    /*
     * @api get /admin-api/a/refresh-token 刷新token
     * @version 0.0.1
     * @group admin
     *
     * @param path int refreshToken token
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function refreshToken()
    {
        $this->validate($this->request, [
            'refreshToken' => 'required'
        ]);
        $refreshToken = $this->request->input('refreshToken');
        $result = KongOauthService::refreshToken($refreshToken);
        return $this->sendSuccessJson($result);
    }
}
